<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\Device;
use App\Models\SwitchData;


class BatteryConfig extends Model
{
    protected $table = 'xfy_battery_config';
    protected $primaryKey = 'id';

    public static function setControl($ssn, $op){
        $switch = Device::where('wk_machine_code', $ssn)->first();
        $parent = Device::find($switch['pid']);
        if ($op == 'on') {
            SwitchData::setSwitchOn($parent['wk_machine_code'], $switch['deviceId'], $switch['wk_box_id'], $ssn);
        } elseif ($op == 'off') {
            SwitchData::setSwitchOff($parent['wk_machine_code'], $switch['deviceId'], $switch['wk_box_id'], $ssn);
        }
        sleep(1);
    }

    public static function analysisMessage($topic, $msg) {
        $uniqueCode = 1111;
        $data = json_decode($msg, true);
        Redis::set($uniqueCode, json_encode($data));

        $real = 10;

        for ($i=1; $i < 4; $i++) {
            $levelKey = $uniqueCode.'_level_'.$i;
            $groupKey = $uniqueCode.'_group_'.$i;
            $lowest = Redis::get($levelKey);
            //实时数据小于预设数据，分闸
            if ($lowest < $real) {
                $switchesJson = Redis::get($groupKey);
                $switches = json_decode($switches, true);
                foreach ($switches as $deviceId => $ssn) {
                    $realDataJson = Redis::get($ssn);
                    $realData = json_decode($realDataJson,true);
                    if ($realData['status'] == 1) {
                        self::setControl($ssn, 'off');
                    }
                }
            }
        }
    }

    public static function updateConfig($deviceId, $level, $value){
        $bettery = Device::find($deviceId);
        $levelKey = $bettery['wk_machine_code'].'_level_'.$level;
        $levelValue = floatval($value);
        $config = BatteryConfig::where('device_id', $deviceId)->where('level', $level)->first();
        if (!$config) {
            return false;
        }
        $config->lowest = $levelValue;
        if ($config->save()) {
            Redis::set($levelKey, $levelValue);
            return true;
        } else {
            return false;
        }
    }
}